let ejsExcel=require('ejsexcel');
let fs=require('fs');

let exBuf=fs.readFileSync(__dirname+'/resource/question.xlsx');
ejsExcel.getExcelArr(exBuf).then(exlJson=>{
    console.log("************  read success:getExcelArr");
    let workBook=exlJson;
    let workSheets=workBook[0];
    let questionList =dealExcel(workSheets);
    let tree = filterArray(questionList,'')
    writeJson(tree)

}).catch(error=>{
    console.log("************** had error!");
    console.log(error);
});
function writeJson(questionList){
    //现将json文件读出来
    fs.readFile('./resource/question.json',function(err,data){
        if(err){
            return console.error(err);
        }
        var person = data.toString();//将二进制的数据转换为字符串
        person = JSON.parse(person);//将字符串转换为json对象
        questionList.forEach((item)=>{
            person.data.push(item);//将传来的对象push进数组对象中
        })
        person.total = person.data.length
        var str = JSON.stringify(person);//因为nodejs的写入文件只认识字符串或者二进制数，所以把json对象转换成字符串重新写入json文件中
        fs.writeFile('./resource/question.json',str,function(err){
            if(err){
                console.error(err);
            }
            console.log('----------新增成功-------------');
        })
    })
}
function dealExcel(data){//处理获取的数据
    var dataArr =[]
    var headerArr = data.shift();
    data.forEach((item2)=>{
        var obj = {}
        headerArr.forEach((item,index) => {
          if(index===1){
            obj[item] = item2[index]?item2[index]:""
          } else if(index===3) {
            obj[item] = item2[index]?item2[index].split("。"):[]
          } else if(index===4){
            obj[item] = item2[index]?item2[index].split(","):[]
          }else {
            obj[item] = item2[index]
          }
        });
        dataArr.push(obj)
    })
    return dataArr
}
function filterArray(data, parent) {//转换成树状结构
    let vm = this;
    var tree = [];
    var temp;
    for (var i = 0; i < data.length; i++) {
        if (data[i].parentId == parent) {
            var obj = data[i];
            temp = filterArray(data, data[i].id);
            if (temp.length > 0) {
                obj.children = temp;
            }
            tree.push(obj);
        }
    }
    return tree;
}